﻿
using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Core;
using System.Web.UI.HtmlControls;
using System.Configuration;
using System.IO;

namespace Yuanlin.Business
{
    public class NewsEditControl : YuanlinUserControl,
        IReplyConverter<NewsReply, GetOperation>
    {
        protected ValuedTextBox titleValuedTextBox;
        protected ValuedDropDownList provinceDropDownList;
        protected ValuedDropDownList cityDropDownList;
        protected ValuedDropDownList townDropDownList;
        protected ValuedDropDownList smallTownDropDownList;
        protected ValuedDropDownList parentNewsCategoryDropDownList;
        protected ValuedDropDownList childNewsCategoryDropDownList;
        protected CheckBoxList companyTypesCheckBoxList;
        protected ValuedEditor descriptionValuedEditor;
        protected HiddenField townHidden;
        protected HiddenField smallTownHidden;
        protected IButton SaveButton;
        protected IButton BackButton;
        protected FileUpload attachmentData;
        protected CheckBox topCheckBox;

        private News news;

        public override void GetRequests(List<BaseRequestBinder> requestBinders)
        {
            requestBinders.Add(RequestHelper.BuildGetNewsRequest(this));
        }
        protected override void OnLoad(EventArgs e)
        {
            SaveButton.Click += new EventHandler(SaveButton_Click);
            BackButton.Click += new EventHandler(BackButton_Click);
            AjaxManager.Register(this, "AjaxMethod");
        }
        private void Bind()
        {
            if (news == null)
            {
                return;
            }
            this.titleValuedTextBox.Value = news.Title.Value;
            this.descriptionValuedEditor.Value = news.Body.Value;
            topCheckBox.Checked = news.IsTop.Value == 1 ? true : false;

            NewsCategoryListRequest request = new NewsCategoryListRequest();
            request.UpNewsCategoryId = 0;
            EntityList newsCategories = BusinessManager.GetNewsCategoryList(RequestHelper.BuildGetNewsCategoryListRequest(request));

            parentNewsCategoryDropDownList.DataSource = newsCategories;
            parentNewsCategoryDropDownList.DataValueField = "EntityId";
            parentNewsCategoryDropDownList.DataTextField = "Title";
            parentNewsCategoryDropDownList.DataBind();
            parentNewsCategoryDropDownList.Value = news.NewsCategoryId.Value.ToString();

            request = new NewsCategoryListRequest();
            request.UpNewsCategoryId = news.NewsCategoryId.Value;
            EntityList childCategories = BusinessManager.GetNewsCategoryList(RequestHelper.BuildGetNewsCategoryListRequest( request));
            childNewsCategoryDropDownList.DataSource = childCategories;
            childNewsCategoryDropDownList.DataValueField = "EntityId";
            childNewsCategoryDropDownList.DataTextField = "Title";
            childNewsCategoryDropDownList.DataBind();
            childNewsCategoryDropDownList.Value = news.ChildNewsCategoryId.Value.ToString();

            EntityList companys = BusinessManager.GetCompanyTypeList(RequestHelper.BuildGetCompanyTypeListRequest());
            if (companys != null)
            {
                BindCheckBoxList(companyTypesCheckBoxList, companys, "EntityId", "Title", news.CompanyTypes.Value.Trim(','));
            }

            AreaListRequest request1 = new AreaListRequest();
            request1.UpAreaId = 0;
            EntityList areas = BusinessManager.GetAreaList(RequestHelper.BuildGetAreaListRequest(request1));
            if (areas == null)
                return;
            BindDropDownList(provinceDropDownList, areas, "EntityId", "Title", news.Province.Value.ToString());
            if (this.provinceDropDownList.SelectedValue.Length == 0)
                return;

            request1 = new AreaListRequest();
            request1.UpAreaId = Convert.ToInt32(this.provinceDropDownList.SelectedValue);
            areas = BusinessManager.GetAreaList(RequestHelper.BuildGetAreaListRequest(request1));
            if (areas == null)
                return;
            BindDropDownList(cityDropDownList, areas, "EntityId", "Title", news.City.Value.ToString());
            if (this.cityDropDownList.SelectedValue.Length == 0)
                return;

            request1 = new AreaListRequest();
            request1.UpAreaId = Convert.ToInt32(this.cityDropDownList.SelectedValue);
            areas = BusinessManager.GetAreaList(RequestHelper.BuildGetAreaListRequest(request1));
            if (areas == null)
                return;
            BindDropDownList(townDropDownList, areas, "EntityId", "Title", news.Town.Value.ToString());
            if (this.townDropDownList.SelectedValue.Length == 0)
                return;

            request1 = new AreaListRequest();
            request1.UpAreaId = Convert.ToInt32(this.townDropDownList.SelectedValue);
            areas = BusinessManager.GetAreaList(RequestHelper.BuildGetAreaListRequest(request1));
            if (areas == null)
                return;
            BindDropDownList(smallTownDropDownList, areas, "EntityId", "Title", news.SmallTown.Value.ToString());
        }
        private void BindDropDownList(ValuedDropDownList ddl, EntityList list, string valueField, string textField, string selectedValue)
        {
            ddl.DataSource = list;
            ddl.DataValueField = valueField;
            ddl.DataTextField = textField;
            ddl.DataBind();
            if (selectedValue.Length > 0)
            {
                ddl.Value = selectedValue;
            }
        }
        private void BindCheckBoxList(CheckBoxList cbl, EntityList list, string valueField, string textField, string selectedValue)
        {
            cbl.DataSource = list;
            cbl.DataValueField = valueField;
            cbl.DataTextField = textField;
            cbl.DataBind();

            if (selectedValue == null)
            {
                return;
            }

            string[] selectedStr = selectedValue.Split(',');
            if (selectedStr.Length == 0)
            {
                return;
            }

            List<string> selectedList = new List<string>();
            foreach (string itemStr in selectedStr)
            {
                selectedList.Add(itemStr);
            }

            foreach (ListItem item in cbl.Items)
            {
                if (selectedList.Contains(item.Value))
                {
                    item.Selected = true;
                }
            }
        }
        public void BackButton_Click(object sender, EventArgs e)
        {
            PageRedirect();
        }
        public void SaveButton_Click(object sender, EventArgs e)
        {
            if (news != null)
            {
                news.Title.Value =  CensorWordManager.CensorWord(this.titleValuedTextBox.Value);
                news.Body.Value =  CensorWordManager.CensorWord(this.descriptionValuedEditor.Value);
                news.NewsCategoryId.Value = int.Parse(parentNewsCategoryDropDownList.Value);
                news.ChildNewsCategoryId.Value = int.Parse(this.Page.Request.Form[this.childNewsCategoryDropDownList.UniqueID]);
                news.Province.Value = Convert.ToInt32(provinceDropDownList.Value);
                news.City.Value = Convert.ToInt32(cityDropDownList.Value);
                news.IsTop.Value = topCheckBox.Checked ? 1 : 0;

                if (!string.IsNullOrEmpty(townHidden.Value))
                {
                    news.Town.Value = Convert.ToInt32(townHidden.Value);
                }
                if (!string.IsNullOrEmpty(smallTownHidden.Value))
                {
                    news.SmallTown.Value = Convert.ToInt32(smallTownHidden.Value);
                }

                string companyTypes = string.Empty;
                foreach (ListItem item in companyTypesCheckBoxList.Items)
                {
                    if (item.Selected)
                    {
                        companyTypes += "," + item.Value;
                    }
                }
                if (companyTypes.Length > 0)
                {
                    companyTypes = companyTypes + ",";
                }
                news.CompanyTypes.Value = companyTypes;

                news.CreateDate.Value = DateTime.Now;

                if (SiteUrls.Instance().IsAttachmentValid(attachmentData))
                {
                    SiteUrls.Instance().DeleteFile(SiteUrls.Instance().GetFile(news));
                    news.AttachmentFileName.Value = SiteUrls.Instance().GetPostedFileName(attachmentData);
                    SiteUrls.Instance().SaveFile(SiteUrls.Instance().GetFile(news), attachmentData);
                }
                BusinessManager.UpdateNews(news);
            }
            PageRedirect();
        }
        private void PageRedirect()
        {
            Page.Response.Redirect(SiteUrls.Instance().GetNewsListUrl());
        }

        #region Ajax Method

        [AjaxMethod(IncludeControlValuesWithCallBack = false)]
        public string GetChildCategories(int parentCategoryID)
        {
            if (parentCategoryID == -1)
            {
                return string.Empty;
            }

            //得到子列表的集合
            NewsCategoryListRequest request = new NewsCategoryListRequest();
            request.UpNewsCategoryId = parentCategoryID;
            EntityList categories = BusinessManager.GetNewsCategoryList(RequestHelper.BuildGetNewsCategoryListRequest(request));
            if (categories.Count > 0)
            {
                string categoryFormat = "{0}:{1}";
                string categoryString = string.Empty;
                foreach (NewsCategory category in categories)
                {
                    categoryString += ";" + string.Format(categoryFormat, category.EntityId.Value.ToString(), category.Title.Value);
                }
                if (categoryString.Length > 0)
                {
                    categoryString = categoryString.Substring(1);
                }
                return categoryString;
            }

            return string.Empty;
        }
        [AjaxMethod(IncludeControlValuesWithCallBack = false)]
        public string GetAreaChildCategories(int parentCategoryID)
        {
            if (parentCategoryID == -1)
            {
                return string.Empty;
            }

            AreaListRequest request = new AreaListRequest();
            request.UpAreaId = parentCategoryID;
            EntityList areas = BusinessManager.GetAreaList(RequestHelper.BuildGetAreaListRequest(request));

            if (areas != null && areas.Count > 0)
            {
                string areaFormat = "{0}:{1}";
                string areaString = string.Empty;
                foreach (Area area in areas)
                {
                    areaString += ";" + string.Format(areaFormat, area.EntityId.Value.ToString(), area.Title.Value);
                }
                if (areaString.Length > 0)
                {
                    areaString = areaString.Substring(1);
                }
                return areaString;
            }

            return string.Empty;
        }

        #endregion

        #region IReplyConverter<NewsReply,GetOperation> Members

        public void ConvertReply(NewsReply reply, GetOperation operation)
        {
            if (reply != null)
            {
                news = reply.Entity as News;

                if (!Page.IsPostBack && !AjaxManager.IsCallBack)
                {
                    Bind();
                }
            }
        }

        #endregion
    }
}